﻿/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

/**
 * @fileSave plugin.
 */

(function () {
    var saveCmd =
	{
	    modes: { wysiwyg: 1, source: 1 },
	    readOnly: 1,
	    exec: function (editor) {
	        DIF.checkFieldItem(); //检查FieldItem数据是否一致。
	        DIF.setHtmlString(editor.getData());
	        $.ajax({
	            type: "Post",
	            url: "FormSave.aspx/SaveForm",
	            data: DIF.getData(),
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                if (data) {
	                    if (data.d) {
	                        var resp = data.d;
	                        //Successful processing by ckprocess.php should return simply 'OK'.

	                        if (resp.indexOf('OK') >= 0) {
	                            var respArray = resp.split("@");
	                            if (respArray[0] == "OK") {
	                                //This is a custom function I wrote to display messages. Nicer than alert()                  

	                                DIF.loadFormByID(respArray[1]);
	                                alert(editor.lang.formsave.successfully);
	                            } else {
	                                alert(editor.lang.formsave.unsuccessful + resp);
	                            }
	                        }
	                        else {
	                            alert(editor.lang.formsave.unsuccessful + resp);
	                        }
	                    }
	                }
	            },
	            error: function (err) {
	                alert(editor.lang.formsave.error + err);
	            }
	        });


	    }, canUndo: true
	};

    var pluginName = 'save';

    // Register a plugin named "save".
    CKEDITOR.plugins.add(pluginName,
	{
	    init: function (editor) {
	        var command = editor.addCommand(pluginName, saveCmd);
	        command.modes = { wysiwyg: !!(editor.element.$.form) };

	        editor.ui.addButton('Save',
				{
				    label: editor.lang.save,
				    command: pluginName
				});
	    }
	});
})();
